﻿using NHibernate;
using PlusAssistance.DAL.Abstract;
using PlusAssistance.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NHibernate.Linq;
using System.Linq.Expressions;

namespace PlusAssistance.DAL.Concrete
{
    public class Repository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly ISession _session;

        public Repository(ISession session)
        {
            _session = session;
        }

        public void Flush()
        {
            _session.Flush();
        }

        public T GetById(int id)
        {
            return _session.Get<T>(id);
        }

        public IEnumerable<T> All()
        {
            return _session.Query<T>();
        }

        public virtual void Add(T entity)
        {
            _session.Save(entity);
        }

        public virtual void Update(T entity)
        {
            _session.Update(entity);
            Flush();
        }

        public virtual void Delete(T entity)
        {
            _session.Delete(entity);
        }

        public virtual void Delete(int id)
        {
            Delete(GetById(id));
        }

        public virtual T Single(Expression<Func<T, bool>> predicate)
        {
            return _session.Query<T>().SingleOrDefault(predicate);
        }

        public virtual List<T> Where(Expression<Func<T, bool>> predicate)
        {
            return _session.Query<T>().Where(predicate).ToList();
        }

        public virtual IQueryable<T> Filter(Expression<Func<T, bool>> predicate)
        {
            return _session.Query<T>().Where(predicate);
        }

        public virtual PagedList<T> GetPaged<TKey>(Expression<Func<T, bool>> predicate, int pageIndex, int pageSize, List<Func<T, TKey>> orderFuncs = null)
        {
            var results = _session
                .Query<T>()
                .Where(predicate)
                .AsQueryable();

            if (orderFuncs != null && orderFuncs.Any())
            {
                var orderedList = results.OrderBy(orderFuncs.FirstOrDefault());

                for (int i = 1; i < orderFuncs.Count; i++)
                {
                    orderedList = orderedList.ThenByDescending(orderFuncs[i]);
                }
                results = orderedList.AsQueryable();
            }

            return InstancePagedList<TKey>(pageIndex, pageSize, results);
        }

        protected virtual PagedList<T> InstancePagedList<TKey>(int pageIndex, int pageSize, IQueryable<T> results)
        {
            return new PagedList<T>(results, pageIndex, pageSize);
        }

        public bool Exists(Expression<Func<T, bool>> predicate)
        {
            return _session.Query<T>().Count(predicate) > 0;
        }
    }
}
